package com.zyy.zyy.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Create by chenlipeng on 2021/08/20 12:15
 */
//生成验证码
@Controller
public class KaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    
       @GetMapping("/kaptcha")
        public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
            byte [] captchaOutputStream;
           ByteArrayOutputStream imgOutputStream=new ByteArrayOutputStream();
           try {
               //生成验证码字符串并保存到session中
           String verifyCode=defaultKaptcha.createText();
           httpServletRequest.getSession().setAttribute("verifyCode",verifyCode);
           BufferedImage challenge=defaultKaptcha.createImage(verifyCode);
               ImageIO.write(challenge,"jpg",imgOutputStream);
           } catch (IllegalArgumentException | IOException e) {
               httpServletResponse.sendError(httpServletResponse.SC_NOT_FOUND);
               return;
           }
               captchaOutputStream=imgOutputStream.toByteArray();
           httpServletResponse.setHeader("Cache-Control","no-store");
           httpServletResponse.setHeader("Pragma","no-cache");
           
           httpServletResponse.setDateHeader("Expires",0);
           httpServletResponse.setContentType("image/jepg");
           ServletOutputStream responseOutputStream=httpServletResponse.getOutputStream();
           responseOutputStream.write(captchaOutputStream);
           responseOutputStream.flush();
           responseOutputStream.close();
       }
    }
    
